package com.wlanauth.web.action;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Restrictions;

import com.wlanauth.core.criteria.GeneralCriteria;
import com.wlanauth.core.criteria.GeneralCriteriaResult;
import com.wlanauth.core.util.MD5Util;
import com.wlanauth.domain.manage.Operator;
import com.wlanauth.domain.manage.Role;
import com.wlanauth.domain.manage.SystemResource;
import com.wlanauth.service.manage.OperatorService;
import com.wlanauth.web.core.BaseActionSupport;
import com.wlanauth.web.core.JsonResult;
import com.wlanauth.web.core.JsonResultConfig;
import com.wlanauth.web.core.SystemConstants;
/**
 * 操作员Action
 * @author zz
 * @date 2012-5-10
 * @email charles.zz.life@gmail.com
 */
public class OperatorAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;
	
	private Operator entity;
	
	private OperatorService operatorService;
	
	/**
	 * 登陆
	 * @return
	 */
	public String login(){
		if(StringUtils.isBlank(entity.getUsername()) || StringUtils.isBlank(entity.getPassword())){
			this.jsonResult = new JsonResult(this,"用户名或密码不能为空",false);
			return this.actionJsonResult();
		}
		Operator oper = operatorService.getByUsername(entity.getUsername());
		if(oper == null){
			this.jsonResult = new JsonResult(this,"未查询到操作员,用户名:"+entity.getUsername(),false);
		} else {
			if(MD5Util.encode(entity.getPassword()).equals(oper.getPassword())){
				Set<SystemResource> rootRS = new HashSet<SystemResource>();
				
				if(oper.getRole()!=null&&oper.getRole().getSystemResources()!=null){
					Set<SystemResource> resources = oper.getRole().getSystemResources();
					rootRS.addAll(resources);
					for(SystemResource sr:resources){
						cascadeParent(sr,rootRS);
						
					}
				}
				Operator temp = new Operator();
				temp.setId(oper.getId());
				temp.setBirth(oper.getBirth());
				temp.setContactPhone(oper.getContactPhone());
				temp.setDisplayname(oper.getDisplayname());
				temp.setUsername(oper.getUsername());
				temp.setEmail(oper.getEmail());
				temp.setRole(oper.getRole());
				if(temp.getRole()==null)temp.setRole(new Role());
				
				temp.getRole().setSystemResources(rootRS);
				this.request.getSession().setAttribute(SystemConstants.SESSION_OPER_KEY, temp);
				this.jsonResult = new JsonResult(this,"成功",true);
			
			} else {
				this.jsonResult = new JsonResult(this,"密码不正确",false);
			}
		}
		return this.actionJsonResult();
	}
	
	private void cascadeParent(SystemResource sr,Set<SystemResource> root) {
		if(StringUtils.isNotBlank(sr.getParentId())&&!sr.getParentId().equals(SystemResource.ID_ROOT)){
			for(SystemResource tmp:root){
				if(tmp.getId().equals(sr.getParentId())){
					return ;
				}
			}
			SystemResource r = getSystemResourceById(sr.getParentId());
			if(r!=null) {
				root.add(r);
				cascadeParent(r,root);
			}
		} else {
			return ;
		}
	}

	public SystemResource getSystemResourceById(String id){
		GeneralCriteria criteria = new GeneralCriteria(SystemResource.class);
		criteria.add(Restrictions.eq("id", id));
		
		GeneralCriteriaResult<SystemResource> result = criteria.executeQuery();
		if(result.getData()==null||result.getData().size()<1) return null;
		return result.getData().get(0);
	}
	/**
	 * 退出
	 * @return
	 */
	public String logout(){
		Operator oper = (Operator)this.request.getSession().getAttribute(SystemConstants.SESSION_OPER_KEY);
		if(oper == null){
			this.jsonResult = new JsonResult(this,"已退出",false);
		} else {
			this.request.getSession().setAttribute(SystemConstants.SESSION_OPER_KEY, null);
			this.request.getSession().removeAttribute(SystemConstants.SESSION_OPER_KEY);
			this.jsonResult = new JsonResult(this,"退出成功",true);
		}
		return this.actionJsonResult();
	}
	/**
	 * 保存
	 * @return
	 */
	public String save(){
		Operator temp = this.operatorService.getByUsername(entity.getUsername());
		if(temp!=null){
			this.jsonResult = new JsonResult(this,"该用户已存在,用户名:"+entity.getUsername(),false);
			return this.actionJsonResult();
		}
		this.entity.setPassword(MD5Util.encode(this.entity.getPassword()));
		this.operatorService.save(entity);
		
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	/**
	 * 编辑
	 * @return
	 */
	public String edit(){
		Operator temp = this.operatorService.get(entity.getId());
		JsonResultConfig cfg = new JsonResultConfig();
		cfg.setExcludeProperties(new String[]{
				".*.role\\.systemResources",
				".*.password"
		});
		this.jsonResult = new JsonResult(this,temp,true);
		return this.actionJsonResult(cfg);
	}
	public String update(){
		Operator oper = this.operatorService.get(entity.getId());
		if(!oper.getUsername().equals(entity.getUsername())){
			Operator temp = this.operatorService.getByUsername(entity.getUsername());
			if(temp!=null){
				this.jsonResult = new JsonResult(this,"该用户已存在,用户名:"+entity.getUsername(),false);
				return this.actionJsonResult();
			}
		}
		oper.setAddress(entity.getAddress());
		oper.setBirth(entity.getBirth());
		oper.setContactPhone(entity.getContactPhone());
		oper.setDescription(entity.getDescription());
		oper.setDisplayname(entity.getDisplayname());
		oper.setEmail(entity.getEmail());
		oper.setRole(entity.getRole());
		oper.setSexId(entity.getSexId());
		oper.setUsername(entity.getUsername());
		oper.setPassword(MD5Util.encode(this.entity.getPassword()));
		this.operatorService.update(oper);
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	public String delete(){
		this.operatorService.deleteByKey(this.entity.getId());
		this.jsonResult = new JsonResult(this,true);
		return this.actionJsonResult();
	}
	/**
	 * 显示
	 * @return
	 */
	public String list(){
		//通用查询
		GeneralCriteria criteria = this.buildWebQueryCriteria(Operator.class);
		
		if(entity!=null){
			if(entity.getUsername()!=null){
				criteria.add(Restrictions.eq("username", entity.getUsername()));
			}
			if(entity.getDisplayname()!=null){
				criteria.add(Restrictions.eq("displayname", entity.getDisplayname()));
			}
			if(entity.getEmail()!=null){
				criteria.add(Restrictions.eq("email", entity.getEmail()));
			}
		}
		
		GeneralCriteriaResult<Operator> result = criteria.executeQuery();
		if(result.getData()!=null){
			for(Operator p:result.getData()){
				criteria.initialize(p.getRole());
			}
		}
		JsonResultConfig cfg = new JsonResultConfig();
		cfg.setExcludeProperties(new String[]{
				".*.systemResources"
		});
		this.jsonResult = new JsonResult(this,result.getData(),result.getTotal());
		return this.actionJsonResult(cfg);
	}
	
	
	public Operator getEntity() {
		return entity;
	}

	public void setEntity(Operator entity) {
		this.entity = entity;
	}

	public void setOperatorService(OperatorService operatorService) {
		this.operatorService = operatorService;
	}
}
